package com.lujieni.dbsharding.simple.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * @Package: com.lujieni.dbsharding.simple.sharding
 * @ClassName: TablePreciseShardingAlgorithm
 * @Author: lujieni
 * @Description: 分表算法
 * @Date: 2021-04-25 16:47
 * @Version: 1.0
 */
public class TablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    private static final Logger logger = LoggerFactory.getLogger(TablePreciseShardingAlgorithm.class);

    /**
     *
     * @param collection  t_order_${0..1} t_order_0 t_order_1
     * @param preciseShardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        for (String each : collection) {
            //t_order_0 t_order_1
            //计算分片键的hashcode，再除以15，再取模，防止直接取模结果和数据库分配算法一致导致的只分库未分表
            if (each.substring(each.lastIndexOf("_")).equals("_" + (Math.abs(preciseShardingValue.getValue().hashCode()) / 15 % 2))) {
                logger.info("sharding key {}, sharding result {}", preciseShardingValue.getValue(), each);
                return each;
            }
        }
        logger.info("error");
        return null;
    }

}